
package com.wlsk.license.service.zpff;

import com.alibaba.fastjson.JSONObject;
import com.wlsk.license.common.utils.Sm4Util;
import com.wlsk.license.config.Global;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 道路运输管理局 Road Transport Administrative Bureau
 */
public class RtabHelper {

    // 运管请求用户名
    private static final Logger LOGGER = LoggerFactory.getLogger(RtabHelper.class);

    public static byte[] downloadFromTransportation(String filePath) throws Exception {
        // 获取token并传输token
        String token = RtabTokenHelper.getToken();
        // 组成URL
        String urlParam = CharterApplyLicense.ATTACHMENT_DOWNLOAD_URL_STRING + "?token=" + token;
        // 对参数进行加密
        JSONObject json = new JSONObject();
        LOGGER.info(filePath);
        json.put("filepath", filePath);
        String body = Sm4Util.encryptEcb(RtabTokenHelper.KEY, json.toString());
        urlParam = urlParam + "&body=" + body;
        urlParam = urlParam + "&username=" + RtabTokenHelper.USERNAME;
        LOGGER.info(urlParam);
        URL url = new URL(urlParam);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        InputStream is = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            is = conn.getInputStream();
            IOUtils.copy(is, os);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }

        return os.toByteArray();
    }

    public static RtabResult handleResponse(String resultStr) {
        RtabResult result = JSONObject.parseObject(resultStr, RtabResult.class);
        RtabResultCode resultCode = RtabResultCode.valueToCode(result.getCode());
        result.setResultCode(resultCode);
        return result;
    }
}
